package com.ruoyi.web.core.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.modules.service.TRwbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监听websocket地址/监听
 */
@Component
@ServerEndpoint("/myWs1")
@Slf4j
public class WebServerEndpont1 {
    @Autowired
    private TRwbService tRwbService;
    static Map<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        sessions.put(session.getId(), session);
        log.info("websocket is open");
    }
    @OnMessage
    public String onMessage(String message) {
        log.info("websocket message received: " + message);
        log.info("收到了一条消息："+message);
        return "";
    }
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session.getId());
        log.info("websocket is close");
    }
    @Scheduled(fixedRate = 30000)
    public void sendMsg() throws EncodeException, IOException {
        for (String key : sessions.keySet()) {
            AjaxResult ajaxResult = tRwbService.getDepartmentList(new HashMap<>());
            ArrayList list =(ArrayList) ajaxResult.get("data1");
            ObjectMapper objectMapper = new ObjectMapper();
            sessions.get(key).getBasicRemote().sendText(objectMapper.writeValueAsString(list));
        }
    }

}
